package com.foreknow.hospital.dao.impl;

import com.foreknow.hospital.dao.UserDao;
import com.foreknow.hospital.po.User;

import com.foreknow.hospital.util.DBUtil;

import java.sql.*;

import static com.foreknow.hospital.util.DBUtil.getConnection;

public class UserDaoImpl implements UserDao {
    // 获取数据库连接
    private Connection con;
    private PreparedStatement pst;
    private ResultSet rs;

    @Override
    public User getUsersByUserIdByPass(String userId, String password) throws SQLException {
        User users = new User();
       String sql = "select * from users where userId = ? and password = ?";
       try {
           con = getConnection();
            pst = con.prepareStatement(sql);
            pst.setString(1, userId);
            pst.setString(2, password);
            rs = pst.executeQuery();
            if(rs.next()){

                users.setUserId(rs.getString("userId"));
                users.setPassword(rs.getString("password"));
                users.setRealName(rs.getString("realName"));
                users.setSex(rs.getInt("sex"));
                users.setIdentityCard(rs.getString("identityCard"));
                users.setBirthday(rs.getString("birthday"));
                users.setUserType(rs.getInt("userType"));
            }
       }finally {
           DBUtil.close(pst);
       }return  users;
    }

    @Override
    public User getUsersById(User users) throws SQLException{
        boolean isRegistered=false;
        String sql = "select userId from users where userId = ?";
        try{
            con = getConnection();
            pst = con.prepareStatement(sql);
            pst.setString(1, users.getUserId());
            rs = pst.executeQuery();
            if(rs.next()){
                isRegistered=true;
            }
        }finally {
            DBUtil.close(pst);
        }
        //当用户已注册（isRegistered为true）时返回用户对象users，未注册时返回null
        return isRegistered ? users : null;
    }

    @Override
    public int saveUsers(User users) throws SQLException {
        int result=0;
        String sql = "insert into users (userId, password, realName, sex, identityCard, birthday,userType) values (?, ?, ?, ?, ?,?,?)";
        try{
            con = getConnection();
            pst= con.prepareStatement(sql);
            pst.setString(1, users.getUserId());
            pst.setString(2, users.getPassword());
            pst.setString(3, users.getRealName());
            pst.setInt(4, users.getSex());
            pst.setString(5, users.getIdentityCard());
            pst.setString(6, users.getBirthday());
            users.setUserType(1);
            pst.setInt(7, users.getUserType());
            result = pst.executeUpdate();
        }finally {
            DBUtil.close(pst);
        }
        return result;
    }
}
